<template>
  <div id="app">
    <div>
      <span>姓名:</span>
      <input type="text" v-model.trim="user.name" />
    </div>
    <div>
      <span>年龄:</span>
      <input type="number" v-model.number="user.age" />
    </div>
    <div>
      <span>性别:</span>
      <select v-model="user.sex">
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
    </div>
    <div>
      <button @click="add">添加/修改</button>
    </div>
    <div>
      <table border="1" cellpadding="10" cellspacing="0">
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tr v-for="(val, index) in list" :key="index">
          <td>{{ val.id }}</td>
          <td>{{ val.name }}</td>
          <td>{{ val.age }}</td>
          <td>{{ val.sex }}</td>
          <td>
            <button @click="del(index)">删除</button>
            <button @click="edit(val, index)">编辑</button>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      editindex: -1,
      user: {
        id: "",
        name: "",
        age: "0",
        sex: "",
      },
      list: [
        {
          id: 100,
          name: "Tom",
          age: 19,
          sex: "男",
        },
        {
          id: 101,
          name: "Jone",
          age: 21,
          sex: "女",
        },
      ],
    };
  },
  methods: {
    add() {
      if (this.editindex === -1) {
        this.user.id =
          this.list.length === 0 ? 100 : this.list[this.list.length - 1].id + 1;
        this.list.push({ ...this.user });
      } else {
        this.$set(this.list, this.editindex, { ...this.user });
      }
    },
    del(index) {
      this.list.splice(index, 1);
    },
    edit(theobj, index) {
      console.log(theobj);
      this.user = { ...theobj };
      this.editindex = index;
    },
  },
};
</script>